<template>
  <div
    class="o-modal"
    :style="showAnimation"
    @mouseup="dragEnd"
    @mousemove="dragMove"
  >
    <div
      class="back"
      @click="!!tapClose ? close() : () => {}"
      :style="{ background: !!mask ? 'rgba(0, 0, 0, 0.5)' : 'transparent' }"
    ></div>
    <div
      class="front"
      ref="oModal"
      :style="{
        width: size[0] + 'px',
        height: size[1] ? size[1] + 'px' : 'auto',
        left: `${(screenSize.w - size[0]) / 2}px`,
        top: size[1] ? `${(screenSize.h - size[1]) / 2}px` : '20%'
      }"
    >
      <div class="box" v-if="keepAlive ? true : isRender">
        <div class="header" @mousedown="dragStart">
          <span>{{ title }}</span>
          <div class="header-buttons">
            <o-tool-button
              class="expand-btn"
              type="switch"
              :background="false"
              :switchlist="[
                { icon: 'wy-icon wy-ios-expand', value: false },
                { icon: 'wy-icon wy-ios-contract', value: true }
              ]"
              @on-click="expandChange"
            ></o-tool-button>
            <div class="close-btn" @click="close">
              <Icon type="ios-close" />
            </div>
          </div>
        </div>
        <div class="content">
          <slot name="content"></slot>
        </div>
        <div class="footer" v-if="showFooter">
          <div class="footer-btn">
            <div class="custom-footer">
              <slot name="footer"></slot>
            </div>
            <Button v-if="onPrevious !== null" @click="previousClicked">
              {{ $srv.getI18nByPath('others.prevStep') }}</Button
            >
            <Button v-if="onNext !== null" @click="nextClicked">
              {{ $srv.getI18nByPath('others.nextStep') }}</Button
            >
            <Button v-if="onCancel !== null" @click="cancelClicked">
              <!-- 取消 -->
              {{ $srv.getI18nByPath('others.cancel') }}
            </Button>
            <Button type="primary" v-if="onOK !== null" @click="okClicked">{{
              ok || okdefault
            }}</Button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { T_srv, Tsrv, vue } from '@/services';

@T_srv.comp
export default class oModal extends vue {
  /**
   * Props
   */
  @T_srv.prop({
    required: false,
    type: String,
    default: 'modal'
  })
  title: string;

  @T_srv.prop({
    type: String
    // default: "确定"
  })
  ok: string;

  @T_srv.prop({
    required: false,
    type: Array,
    default: [300, 200]
  })
  size: Array<number>;

  @T_srv.prop({
    type: Boolean,
    default: true
  })
  mask?: boolean;

  @T_srv.prop({
    type: Boolean,
    default: true
  })
  tapClose?: boolean;

  @T_srv.prop({
    type: Boolean,
    default: false
  })
  keepAlive: boolean;

  @T_srv.prop({
    type: Boolean,
    default: true
  })
  showFooter: boolean;

  // 向导模式
  @T_srv.prop({
    type: Array,
    default: () => []
  })
  guide: Array<string>;

  @T_srv.model('change', { type: Boolean }) value!: boolean;

  @T_srv.watch('value')
  onValueChange(val: boolean) {
    if (val) {
      this.show();
    } else {
      this.hide();
    }
  }

  public okdefault: string = Tsrv.getI18nByPath('others.ok') as string;

  public oModal: HTMLElement = null;

  public showAnimation = {};

  public onOK = null;

  public onCancel = null;

  public onNext = null;

  public onPrevious = null;

  public drag = {
    start: false,
    divX: 0,
    divY: 0,
    mouseX: 0,
    mouseY: 0
  };

  public screenSize = {
    w: 0,
    h: 0
  };

  public isRender: boolean = false;

  public boundBeforeExpand: any = {};

  // public zIndex = 102;
  public zIndex = 202;

  created() {
    this.onValueChange(this.value);
  }

  mounted() {
    this.oModal = this.$refs.oModal as HTMLElement;

    // 向导模式
    if (this.guide.length > 0) {
      this.guide.forEach(ele => {
        switch (ele) {
          case `onPrevious`:
            this.onPrevious = (this.$listeners['on-previous'] as Function[])[
              'fns'
            ];
            break;
          case `onNext`:
            this.onNext = (this.$listeners['on-next'] as Function[])['fns'];
            break;
          case `onOk`:
            this.onOK = (this.$listeners['on-ok'] as Function[])['fns'];
            break;

          default:
            break;
        }
      });
    } else {
      if (this.$listeners['on-ok']) {
        this.onOK = (this.$listeners['on-ok'] as Function[])['fns'];
      }
      if (this.$listeners['on-cancel']) {
        this.onCancel = (this.$listeners['on-cancel'] as Function[])['fns'];
      }
    }

    // this.zIndex = 102 + this.$store.getters.ModalCount;
    this.zIndex = 202 + this.$store.getters.ModalCount;
  }

  beforeDestory() {
    this.isRender = false;
  }

  private expandChange(val) {
    const divRect = this.oModal.getBoundingClientRect();
    if (val) {
      this.boundBeforeExpand = divRect;
      this.oModal.style.cssText = 'width:100%;height:100%;left:0;top:0';
    } else {
      this.oModal.style.cssText = `width:${this.boundBeforeExpand.width}px;height:${this.boundBeforeExpand.height}px;left:${this.boundBeforeExpand.left}px;top: ${this.boundBeforeExpand.top}px`;
    }
  }

  private okClicked() {
    this.onOK();
  }

  private cancelClicked() {
    this.close();
    this.onCancel();
  }

  private previousClicked() {
    this.onPrevious();
  }

  private nextClicked() {
    this.onNext();
  }

  private close(P_e: any = undefined) {
    // 判断是否窗口按下关闭换扭
    let isFormClickClose: boolean = false;
    // 如果关闭时不希望退出modal传入一个bool为true,但需要你在代码中手工关闭它
    if (typeof P_e === `boolean` && P_e === true) {
      isFormClickClose = true;
    }
    this.hide(isFormClickClose);
  }

  /**
   * @Author: wiz
   * @param {*}
   * @return {*}
   * @description: 隐藏窗口
   */
  public hide(P_e: boolean = false) {
    const that = this;
    this.$emit('change', P_e);
    this.$emit('on-close', P_e);
    this.showAnimation = {
      display: 'block',
      opacity: 0,
      'z-index': this.zIndex
    };
    setTimeout(() => {
      that.showAnimation = {
        display: 'none',
        'z-index': this.zIndex
      };
      this.isRender = false;
    }, 200);
  }

  public show() {
    this.screenSize.w = document.body.offsetWidth;
    this.screenSize.h = document.body.offsetHeight;
    this.$emit('on-open', true);
    this.isRender = true;
    const that = this;
    this.showAnimation = {
      display: 'block',
      'z-index': this.zIndex
    };
    setTimeout(() => {
      that.showAnimation = {
        display: 'block',
        opacity: 1,
        'z-index': this.zIndex
      };
    }, 10);
  }

  private dragStart(e) {
    if (this.oModal !== null) {
      const drag = this.drag;
      // 拖拽开始时鼠标的位置
      drag.mouseX = e.pageX;
      drag.mouseY = e.pageY;
      const divRect = this.oModal.getBoundingClientRect();
      // 拖拽开始时box的位置
      drag.divX = divRect.left;
      drag.divY = divRect.top;
      // 开始拖拽
      drag.start = true;
    }
  }

  private dragEnd() {
    if (this.oModal !== null) {
      // 结束拖拽
      this.drag.start = false;
    }
  }

  private dragMove(e) {
    if (this.oModal !== null) {
      const drag = this.drag;
      if (drag.start) {
        // 当前鼠标的位置
        const curX = e.pageX;
        const curY = e.pageY;
        // 鼠标的变化
        const disX = curX - drag.mouseX;
        const disY = curY - drag.mouseY;
        // 应改变box的位置
        const styleX = drag.divX + disX;
        const styleY = drag.divY + disY;
        this.oModal.style.left = `${styleX}px`;
        this.oModal.style.top = `${styleY}px`;
      }
    }
  }
}
</script>
<style scoped lang="scss">
.o-modal {
  position: fixed;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  opacity: 0;
  display: none;
  transition: ease-in-out 0.2s;
  .back {
    width: 100%;
    height: 100%;
  }
  .front {
    position: absolute;
    left: 0;
    top: 0;
    .box {
      width: 100%;
      height: 100%;
      // background-color: #fff;
      background-color: var(--model-bg-color);
      display: flex;
      flex-direction: column;
      border-radius: var(--default-border-radius-base);
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
      overflow: hidden;
      border: 1px solid #eee;
      .header {
        width: 100%;
        position: relative;
        height: 48px;
        background-color: rgba(244, 244, 244, 0.7);
        border-bottom: 1px solid rgba(244, 244, 244, 1);
        padding: 0 20px;
        z-index: 11;
        cursor: all-scroll;
        display: flex;
        align-items: center;
      }
      .content {
        width: 100%;
        flex: 1;
        overflow: hidden;
        // padding: 10px 0 20px 0;
        padding: 5px 0 10px 0;
      }
      .footer {
        height: 50px;
        width: 100%;
        overflow: hidden;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        .footer-btn {
          float: right;
          button {
            float: left;
            margin-right: 15px;
          }
          .custom-footer {
            float: left;
          }
        }
      }
    }
  }
}
.header {
  .header-buttons {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
  > span {
    font-size: 14px;
    font-weight: bold;
    line-height: 46px;
    color: #666;
    pointer-events: none;
    user-select: none;
  }

  .close-btn {
    width: 28px;
    height: 28px;
    cursor: pointer;
    color: #666;
    .ivu-icon {
      font-size: 28px;
      font-weight: bold;
    }
  }
  .expand-btn ::v-deep {
    .ivu-icon {
      font-size: 16px;
      font-weight: bold;
    }
  }
}
</style>
